package com.peaker.advertisingpro.utils

import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Rect
import android.graphics.pdf.PdfRenderer
import android.os.Build
import android.os.ParcelFileDescriptor
import android.util.Log
import java.io.File
import java.lang.ref.SoftReference

/**
 * pdf装bitmap 工具类
 */
object pdfUtils {

    fun pdfToBitmap(pdfFile: File, resources: Resources): ArrayList<Bitmap>? {
        val bitmaps: ArrayList<Bitmap> = ArrayList()
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                val renderer = PdfRenderer(
                    ParcelFileDescriptor.open(
                        pdfFile,
                        ParcelFileDescriptor.MODE_READ_ONLY
                    )
                )
                var bitmap: Bitmap
                var softReferenceBitmap:SoftReference<Bitmap>
                val pageCount = renderer.pageCount
                Log.e("test_sign", "图片de 张数： $pageCount")
                for (i in 0 until pageCount) {
                    val page = renderer.openPage(i)
                    val width = resources.displayMetrics.densityDpi / 160 * page.width
                    val height = resources.displayMetrics.densityDpi / 160 * page.height
//                    bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
                     softReferenceBitmap = SoftReference(Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888))

                    //todo 以下三行处理图片存储到本地出现黑屏的问题，这个涉及到背景问题
                    val canvas = Canvas(softReferenceBitmap.get())
                    canvas.drawColor(Color.WHITE)
                    canvas.drawBitmap(softReferenceBitmap.get(), 0f, 0f, null)
                    val r = Rect(0, 0, width, height)
                    page.render(softReferenceBitmap.get(), r, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
                    bitmaps.add(softReferenceBitmap.get()!!)
                    // close the page
//                    softReferenceBitmap.get()!!.recycle()
                    page.close()
                }

                System.gc()
                // close the renderer
                renderer.close()
            }
        } catch (ex: Exception) {
            ex.printStackTrace()
        }
        return bitmaps
    }
}